package com.szwistar.common.datastruct;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.szwistar.common.os.FileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class XmlMapper2 {
	static final XmlMapper xmlMapper = new XmlMapper();
	public static XmlMapper getMapper() { return xmlMapper; }

	static {
		// 设置属性: 遇到不可识别的属性时，继续编码
		getMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		// 设置属性: 遇到不可识别的属性时，继续解析
		getMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	public static String toXml(Object obj) throws JsonProcessingException {
		return getMapper().writeValueAsString(obj);
	}

	public static <T> T fromXml(String xml, Class<? extends T> typeClass) throws Exception {
		if((xml == null) || xml.isEmpty() || (typeClass ==null)) { return null; }
		return getMapper().readValue(xml, typeClass);
	}

	public static <T> T[] fromXmlAsArrayOf(String xml, Class<? extends T> typeClass) throws Exception {
		if((xml == null) || xml.isEmpty() || (typeClass ==null)) { return null; }
		JavaType type = getMapper().getTypeFactory().constructArrayType(typeClass);
		return getMapper().readValue(xml, type);
	}

	public static <T> ArrayList<T> fromXmlAsListOf(String xml, Class<? extends T> typeClass) throws Exception {
		if((xml == null) || xml.isEmpty() || (typeClass ==null)) { return null; }
		JavaType type = getMapper().getTypeFactory().constructCollectionType(ArrayList.class, typeClass);
		return getMapper().readValue(xml, type);
	}

	public static <K,T> Map<K,T> fromXmlAsMapOf(String xml, Class<? extends K> keyClass, Class<? extends T> valueClass) throws Exception {
		if((xml == null) || xml.isEmpty() || (keyClass ==null) || (valueClass ==null)) { return null; }
		JavaType type = getMapper().getTypeFactory().constructMapType(HashMap.class, keyClass, valueClass);
		return getMapper().readValue(xml, type);
	}

	/**
	 * 默认情况下，转化为Map<String, Object>
	 */
	public static JsonObject fromXml(String xml) throws Exception {
		if(Utils.isEmpty(xml)) { return null; }
        //JavaType type = getMapper().getTypeFactory().constructMapType(HashMap.class, String.class, Object.class);
        //return getMapper().readValue(xml, type);
		JsonObject ret = fromXml(xml, JsonObject.class);
		return ret;
	}

	public static void main(String[] args) throws Exception {
		String xml = FileUtils.readFileAsString("test/test.xml");
		JsonObject obj = fromXml(xml);
		xml = toXml(obj);
	}
}
